package com.anlogic.sdk.startup;

import java.util.List;

import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import com.anlogic.sdk.env.utils.EnvCheckUtils;
import com.anlogic.sdk.startup.utils.Utils;
import com.anlogic.sdk.tools.ui.BspToolView;
import com.anlogic.sdk.utils.EnvUtils;
import com.anlogic.sdk.utils.LogUtils;
import com.anlogic.sdk.utils.UIUtils;
import com.anlogic.sdk.workspace.FDWorkspace;

public class InitSDK implements IStartup {
	private static Logger logger = LogUtils.getLogger(InitSDK.class);

	@Override
	public void earlyStartup() {
		IWorkbench workbench = PlatformUI.getWorkbench();
		workbench.getDisplay().asyncExec(new Runnable() {
			public void run() {
				if (!Utils.licenseExeExists()) {
					MessageDialog.openError(null, "License Validation", "License verify execute doesen't exist!");
					workbench.close();
				}
				logger.info("Validate License...");
				if (!LicenseHandler.validate()) {
					logger.info("Validate License done");
					workbench.close();
				}
				logger.info("Validate License done");
				checkEnvironment();
				startBspCli();
				checkWorkspace();
				
			}
		});
	}

	public void checkWorkspace() {
		logger.info("Check workspace...");
		EnvCheckUtils envCheckUtils = new EnvCheckUtils();
		String msg = envCheckUtils.checkWorkspace();
		IProject[] projects = EnvUtils.getWorkspaceProjects();
		IProject[] unMatchedProjects = EnvUtils.getUnMatchedProjects();
		if (!msg.isEmpty() && projects.length != 0) {
			msg = "The workspace version is inconsistent with the current software version. Projects may not open or compile properly. Click OK to reset the workspace and projects, click Cancel to open only the workspace.";
			openResetDialog(msg);
		} else if (projects.length != 0 && projects.length == unMatchedProjects.length) {
			msg = "The workspace may be opened for the first time. Click OK to reset the workspace and projects, click Cancel to open only the workspace.";
			openResetDialog(msg);
		} else if (projects.length == 0 && envCheckUtils.wsHasUnimportedProjects()) {
			msg = "The workspace may be opened for the first time. Click OK to import projects and reset the workspace, click Cancel to open only the workspace.";
			openImportResetDialog(msg);
		}
		
		FDWorkspace ws = new FDWorkspace();
		if (!ws.propertyFileExists()) {
			ws.createNewPropertyFile();
		}
		
		envCheckUtils.reportProjectProblem(EnvUtils.getWorkspaceProjects());
		logger.info("Check workspace done");
	}
	
	public void openResetDialog(String msg) {
		EnvCheckUtils envCheckUtils = new EnvCheckUtils();
		boolean ret = MessageDialog.openConfirm(null, "Workspace Check", msg);
		if (ret) {
			Job job = new Job("Reset Workspace") {
				@Override
				protected IStatus run(IProgressMonitor monitor) {
					logger.info("Reset workspace...");
					String errMsg = envCheckUtils.resetWorkspace();
					if (errMsg != null && !errMsg.isEmpty()) {
						logger.error("Reset workspace failed: {}", errMsg);
						UIUtils.showMessageDialogAsync("Reset workspace", errMsg, MessageDialog.ERROR);
					} else {
						logger.info("Reset workspace successfully!");
						UIUtils.showMessageDialogAsync("Reset workspace", "Reset workspace successfully!", MessageDialog.NONE);
					}
					logger.info("Reset workspace done");
					return Status.OK_STATUS;
				}	
			};
			job.setUser(true);
			job.schedule();
		}
	}
	
	public void openImportResetDialog(String msg) {
		EnvCheckUtils envCheckUtils = new EnvCheckUtils();
		boolean ret = MessageDialog.openConfirm(null, "Workspace Check", msg);
		if (ret) {
			Job job = new Job("Reset Workspace") {
				@Override
				protected IStatus run(IProgressMonitor monitor) {
					logger.info("Import workspace projects...");
					String errMsg = envCheckUtils.importProjects(EnvUtils.getWorkspacePath());
					if (errMsg != null && !errMsg.isEmpty()) {
						logger.error("Import workspace projects failed: {}", errMsg);
					}
					logger.info("Import workspace projects done");
					logger.info("Reset workspace...");
					errMsg = envCheckUtils.resetWorkspace();
					if (errMsg != null && !errMsg.isEmpty()) {
						logger.error("Reset workspace failed: {}", errMsg);
						UIUtils.showMessageDialogAsync("Reset workspace", errMsg, MessageDialog.ERROR);
					} else {
						logger.info("Reset workspace successfully!");
						UIUtils.showMessageDialogAsync("Reset workspace", "Reset workspace successfully!", MessageDialog.NONE);
					}
					logger.info("Reset workspace done");
					return Status.OK_STATUS;
				}	
			};
			job.setUser(true);
			job.schedule();
		}
	}
	
	public void startBspCli() {
		IWorkbench workbench = PlatformUI.getWorkbench();
		Shell shell = workbench.getDisplay().getActiveShell();
		if (shell != null) {
            BspToolView bspToolView = new BspToolView();
            logger.info("Start asct cli...");
            bspToolView.startBackend();
            logger.info("Start asct cli done");
		}
	}
	
	public void checkEnvironment() {
		logger.info("Check environment...");
		List<String> msgList = EnvUtils.checkEnv();
		if (msgList != null && !msgList.isEmpty()) {
			logger.error("Environment check failed!");
			for (String msg : msgList) {
				logger.error("Environment check Failed: " + msg);
			}
			UIUtils.showMessageDialogAsync("Environment Check", "Environment check failed! Please see LoggerView console for more information", MessageDialog.ERROR);
		} else {
			logger.info("Environment check passed");
		}
		logger.info("Check environment done");
	}
}
